package com.duartepeixinho.P3D.Objects.Primitives 
{
	import com.duartepeixinho.P3D.Core.Geom.Face3;
	import com.duartepeixinho.P3D.Core.Math.Vector3;
	import com.duartepeixinho.P3D.Materials.Materials;
	import com.duartepeixinho.P3D.Objects.Mesh;
	/**
	 * P3D
	 * @version 0.1
	 * @author Duarte Peixinho
	 */
	public class Cube extends Mesh
	{
		private var _segments:Vector3;
		
		public function Cube(material:Materials,width:Number = 100, height:Number = 100, depth:Number = 100, segments:uint = 1 ) 
		{			
			this.material = material;
			_segments = new Vector3(segments,segments,segments);			
			
			var width2  :Number = width  /2;
			var height2 :Number = height /2;
			var depth2  :Number = depth  /2;
			
			buildPlane( "front", "x", "y", width, height, depth2, false);
			buildPlane( "back", "x", "y", width, height, -depth2, true);
			buildPlane( "right", "z", "y", depth, height, width2, true);
			buildPlane( "left", "z", "y", depth, height, -width2, false);
			buildPlane( "top", "x", "z", width, depth, height2, true);
			buildPlane( "bottom", "x", "z", width, depth, -height2, false);
			
			
		}	
		private function buildPlane(face:String,u:String,v:String,width:Number,height:Number,depth:Number,reverse:Boolean):void
		{
			
			var w :String;
			if( (u=="x" && v=="y") || (u=="y" && v=="x") ) w = "z";
			else if( (u=="x" && v=="z") || (u=="z" && v=="x") ) w = "y";
			else if( (u=="z" && v=="y") || (u=="y" && v=="z") ) w = "x";
			
			var rev:Number = -1;
			if (reverse) rev = 1;
			
			var gridX:Number = _segments[u];
			var gridY:Number = _segments[v];
			var incU:Number = width / gridX;
			var incV:Number = height / gridY;
			
			// vertices
			var vert:Number = geometry.vertices.length;
			for( var iu:int = 0; iu < gridX + 1; iu++ )
			{
				for( var iv:int = 0; iv < gridY + 1; iv++ )
				{
					var vec:Vector3 = new Vector3();
					vec[u] = (iu * incU - width/2) * rev;
					vec[v] = iv * incV - height/2;
					vec[w] = depth;
					
					geometry.vertices.push( vec );
				}
			}
			
			// faces
			for(  iu = 0; iu < gridX; iu++ )
			{				
				for(  iv = 0; iv < gridY; iv++ )
				{					
					// Triangle A
					var a:Number = iu     * (gridX + 1) + iv + vert;
					var c:Number = iu     * (gridY + 1) + (iv + 1) + vert;
					var b:Number = (iu+1) * (gridY + 1) + iv + vert;
					
					geometry.faces.push(new Face3(this, a, b, c, new Vector3(), material));
					
					// Triangle B
					a = (iu+1) * (gridY + 1) + (iv+1) + vert;
					c = (iu+1) * (gridY + 1) + iv + vert;
					b = iu     * (gridY + 1) + (iv+1) + vert;
					
					geometry.faces.push(new Face3(this, c, a, b, new Vector3(), material));
				}
			}
			
			geometry.calcNormal();
			
		}
		
	}

}